<?php
//计算订单占用库存
class Task_singlecache extends Minion_Task {
	
	//缓存准备
	public function _execute(array $params) {
		set_time_limit ( 0 );
		ini_set('memory_limit','256M');
		
		$echo = '';
		$echo .= "#start op_print_num ".date('Y-m-d h:i:s');

        /**
         * 订单占用库存选取状态
         * erp_orders.orders_status
         * 1新录入
         * 3已通过
         * 4已打印
         * 8缺货
         */
	 		$sql = "SELECT upper(erp_orders_products.orders_sku) AS SKU, 
					SUM( erp_orders_products.item_count ) AS SUM_SKU
					FROM erp_orders_products
					JOIN erp_orders ON erp_orders_products.erp_orders_id = erp_orders.erp_orders_id
					AND erp_orders.orders_status IN (1,3,4,8)
					GROUP BY erp_orders_products.orders_sku";
			
			$re = DB::query(Database::SELECT, $sql)->execute('readonlyerp')->as_array();
			$echo .= "#count ".count($re);
			
			foreach ($re as $r)
			{
				$echo .="#sku".$r['SKU'];
				$op_print_num = Cache::instance()->get($r['SKU'].'_erporderidnum');
				if($op_print_num)
				{
					Cache::instance()->delete($r['SKU'].'_erporderidnum');
				}
				
				$echo .="#sum_sku".$r['SUM_SKU'];
				Cache::instance()->set($r['SKU'].'_erporderidnum',$r['SUM_SKU'],60*60*12);
			} 
			/*
		$result = Cache::instance()->get('skuinfo_');
		
		if(!empty($result)){
 			for($i=0; $i<50000;$i+=500){
				$result2 = array_slice($result,$i,500);
				
				foreach ($result2 as $sku_k =>$_result){
					
					//订单占用库存
					$op_print_num = 0;
					//$op_print_num = Cache::instance()->get($sku_k.'_erporderidnum');
// 					if(empty($op_print_num)){
						$sql = "select erp_orders_id,item_count 
								from erp_orders_products 
								where orders_sku= '".trim($sku_k)."' and item_count>0";
						$erp_orders_ids = DB::query(Database::SELECT,$sql)->execute('readonlyerp')->as_array();
					
						foreach ($erp_orders_ids as $erp_orders_id){
							$sql = "select erp_orders_id 
									from erp_orders 
									where erp_orders_id=".$erp_orders_id['erp_orders_id']." and orders_status =4";
							
							$have = DB::query(Database::SELECT,$sql)->execute('readonlyerp')->current();
							if(isset($have['erp_orders_id'])){
								$op_print_num += $erp_orders_id['item_count'];								
							}
						}
						Cache::instance()->delete($sku_k.'_erporderidnum');
						Cache::instance()->set($sku_k.'_erporderidnum',$op_print_num,60*60*12);
					//}
					$echo.="#sku".$sku_k."#op".$op_print_num;
					//echo $echo;exit;
				}
			}
		} */
		$echo .="#end op_print_num".date('Y-m-d h:i:s');
		echo $echo."\n";
	}
}
